﻿using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Spreadsheet;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using LimaLims.Application.Service.Statistics.Dto;
using LimaLims.Core.Entity.Basic;
using LimaLims.Core.Entity.Equipment;
using LimaLims.Core.Entity.TestCenter;
using LimaLims.Core.Enum;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OBS.Model;
using System.ComponentModel;
using System.Reflection;

namespace LimaLims.Application.Service.Statistics
{
    /// <summary>
    /// 统计服务
    /// </summary>
    [ApiDescriptionSettings(Name = "Statistics", Order = 164)]
    [Route("api")]
    public class StatisticsDataService : IDynamicApiController, ITransient
    {
        private readonly IRepository<ExperimentTask> _experimentTaskRep;
        private readonly IRepository<EquipmentFactory> _equipmentFactoryRep;
        private readonly IRepository<RejectDeal> _rejectDealRep;
        private readonly IRepository<RejectItem> _rejectItemRep;
        private readonly IRepository<DefectiveReason> _defectiveReasonRep;  // 不良原因表仓储
        private readonly IRepository<Team> _teamRep;
        private readonly IRepository<EquipmentInfo> _equipmentRep;  // 设备仪器表仓储
        private readonly IRepository<EquipmentRepair> _equipmentRepairRep;
        private readonly IRepository<EquipmentCategory> _equipmentCategoryRep;//设备分类仓储

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="experimentTaskRep"></param>
        /// <param name="rejectDealRep"></param>
        /// <param name="equipmentRep"></param>
        /// <param name="equipmentRepairRep"></param>
        public StatisticsDataService(IRepository<ExperimentTask> experimentTaskRep, IRepository<EquipmentFactory> equipmentFactoryRep, IRepository<RejectDeal> rejectDealRep, IRepository<EquipmentInfo> equipmentRep, IRepository<EquipmentRepair> equipmentRepairRep, IRepository<EquipmentCategory> equipmentCategoryRep, IRepository<Team> teamRep, IRepository<RejectItem> rejectItemRep, IRepository<DefectiveReason> defectiveReasonRep)
        {
            _equipmentRep = equipmentRep;
            _equipmentFactoryRep = equipmentFactoryRep;
            _experimentTaskRep = experimentTaskRep;
            _rejectDealRep = rejectDealRep;
            _equipmentRepairRep = equipmentRepairRep;
            _equipmentCategoryRep = equipmentCategoryRep;
            _teamRep = teamRep;
            _rejectItemRep = rejectItemRep;
            _defectiveReasonRep = defectiveReasonRep;
        }

        /// <summary>
        /// 获取统计数据
        /// </summary>
        /// <param name="dateType"></param>
        /// <returns></returns>
        [HttpGet("statistics/GetHomeStatisticsData")]
        public async Task<object> GetHomeStatistics(StatisticsDateType dateType)
        {
            var dateRange = GetDates(dateType);

            //试验任务总数
            var TaskItmes = await _experimentTaskRep.DetachedEntities.Where(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= dateRange.StartTime && s.CreatedTime.Value <= dateRange.EndTime).ToListAsync();

            //实际完成试验任务总数
            var FinishTaskItmes = await _experimentTaskRep.DetachedEntities.Where(s => s.ActualEndTime.HasValue && s.ActualEndTime.Value >= dateRange.StartTime && s.ActualEndTime.Value <= dateRange.EndTime).ToListAsync();

            //不良品
            var RejectDealItmes = await _rejectDealRep.DetachedEntities.Where(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= dateRange.StartTime && s.CreatedTime.Value <= dateRange.EndTime).ToListAsync();

            //设备报修
            var RepairItmes = await _equipmentRepairRep.DetachedEntities.Where(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= dateRange.StartTime && s.CreatedTime.Value <= dateRange.EndTime && s.Status != DealStatus.ToBeSubmitted).ToListAsync();

            return new
            {
                TaskCount = TaskItmes.Count(),
                FinishTaskCount = FinishTaskItmes.Count(),
                RejectDealCount = RejectDealItmes.Count,
                RepairCount = RepairItmes.Count(),
            };
        }

        /// <summary>
        /// 试验仪器获取统计数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("statistics/GetEquipmentStatisticsData")]
        public async Task<object> GetEquipmentStatisticsData()
        {
            var equipments = await _equipmentRep.DetachedEntities.CountAsync();
            //设备报修
            var repairItmes = await _equipmentRepairRep.DetachedEntities.Where(s => s.ValidStatus).ToListAsync();

            return new
            {
                EquipmentCount = equipments,
                RepairCount = repairItmes.Count(s => s.Status != DealStatus.ToBeSubmitted),
                NoAcceptedCount = repairItmes.Count(s => s.Status == DealStatus.ToBeDeal || s.Status == DealStatus.ToBeAccept),
                AcceptedCount = repairItmes.Count(s => s.Status == DealStatus.Accepted || s.Status == DealStatus.Rejected)
            };
        }

        /// <summary>
        /// 根据任务状态获取统计数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("statistics/GetTaskStatusStatisticsData")]
        public async Task<object> GetTaskStatusStatisticsData()
        {
            //开工试验任务
            var itmes = await _experimentTaskRep.DetachedEntities.Where(s => s.ValidStatus).ToListAsync();

            return new
            {
                NotStartedCount = itmes.Where(s => s.Status == ExperimentStatus.NotStarted).Count(),
                DoingCount = itmes.Where(s => s.Status == ExperimentStatus.Doing).Count(),
                FinishedCount = itmes.Where(s => s.Status == ExperimentStatus.Finished).Count(),
                PassCount = itmes.Where(s => s.Status == ExperimentStatus.Finished && s.Result.HasValue && s.Result == ExperimentResult.Pass).Count(),
                NoPassCount = itmes.Where(s => s.Status == ExperimentStatus.Finished && s.Result.HasValue && s.Result == ExperimentResult.NoPass).Count(),
            };
        }

        /// <summary>
        /// 根据班组任务统计图
        /// </summary>
        /// <returns></returns>
        [HttpGet("statistics/GetTeamTaskSeriesBarData")]
        public async Task<object> GetTeamTaskSeriesBarData(StatisticsDateType dateType)
        {
            var dateRange = GetDates(dateType);

            List<TeamTaskStatisticsOutput> result = new List<TeamTaskStatisticsOutput>();

            //班组
            var teams = _teamRep.DetachedEntities.Where(s => s.ValidStatus).OrderBy(s => s.Sort).ToList();
            //试验任务
            var taskItmes = await _experimentTaskRep.DetachedEntities.Where(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= dateRange.StartTime && s.CreatedTime.Value <= dateRange.EndTime && s.ValidStatus).ToListAsync();
            //进行任务
            var doingTaskItmes = await _experimentTaskRep.DetachedEntities.Where(s => s.ActualStartTime.HasValue && s.ActualStartTime.Value >= dateRange.StartTime && s.ActualStartTime.Value <= dateRange.EndTime && s.ValidStatus && s.Status == ExperimentStatus.Doing).ToListAsync();
            //完成任务
            var completeTaskItmes = await _experimentTaskRep.DetachedEntities.Where(s => s.ActualEndTime.HasValue && s.ActualEndTime.Value >= dateRange.StartTime && s.ActualEndTime.Value <= dateRange.EndTime && s.ValidStatus && s.Status == ExperimentStatus.Finished).ToListAsync();

            foreach (var itme in teams)
            {
                TeamTaskStatisticsOutput model = new TeamTaskStatisticsOutput
                {
                    TeamName = $"{itme.WorkName}-{itme.Name}",
                    TaskCount = taskItmes.Count(s => s.TeamId == itme.Id),
                    NotStartedCount = taskItmes.Count(s => s.TeamId == itme.Id && s.Status == ExperimentStatus.NotStarted),
                    DoingCount = doingTaskItmes.Count(s => s.TeamId == itme.Id),
                    CompleteCount = completeTaskItmes.Count(s => s.TeamId == itme.Id),
                    PassCount = completeTaskItmes.Count(s => s.TeamId == itme.Id && s.Result == ExperimentResult.Pass),
                    NoPassCount = completeTaskItmes.Count(s => s.TeamId == itme.Id && s.Result == ExperimentResult.NoPass),
                };
                if (model.CompleteCount > 0)
                {
                    double failureRate = (double)model.PassCount / model.CompleteCount;
                    model.PassRate = (failureRate * 100).ToString("F2") + "%";
                }
                result.Add(model);
            }

            SeriesBarData series = new SeriesBarData();

            string[] legends = new string[6];
            legends[0] = "总任务";
            legends[1] = "未开始";
            legends[2] = "进行中";
            legends[3] = "已完成";
            legends[4] = "合格数";
            legends[5] = "不合格";
            series.LegendData = legends;

            series.XAxisData = teams.Select(s => $"{s.WorkName}- {s.Name}").ToList();

            series.yAxisData.Add(new Series { Name = "总任务", Type = "line", Data = result.Select(s => s.TaskCount).ToList() });
            series.yAxisData.Add(new Series { Name = "未开始", Type = "line", Data = result.Select(s => s.NotStartedCount).ToList() });
            series.yAxisData.Add(new Series { Name = "进行中", Type = "line", Data = result.Select(s => s.DoingCount).ToList() });
            series.yAxisData.Add(new Series { Name = "已完成", Type = "line", Data = result.Select(s => s.CompleteCount).ToList() });
            series.yAxisData.Add(new Series { Name = "合格数", Type = "line", Data = result.Select(s => s.PassCount).ToList() });
            series.yAxisData.Add(new Series { Name = "不合格", Type = "line", Data = result.Select(s => s.NoPassCount).ToList() });
            return series;
        }

        /// <summary>
        /// 根据班组任务获取统计数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("statistics/GetTeamTaskStatisticsData")]
        public async Task<object> GetTeamTaskStatisticsData(StatisticsDateType dateType)
        {
            var dateRange = GetDates(dateType);

            List<TeamTaskStatisticsOutput> result = new List<TeamTaskStatisticsOutput>();

            //班组
            var teams = _teamRep.DetachedEntities.Where(s => s.ValidStatus).OrderBy(s => s.Sort).ToList();
            //试验任务
            var taskItmes = await _experimentTaskRep.DetachedEntities.Where(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= dateRange.StartTime && s.CreatedTime.Value <= dateRange.EndTime && s.ValidStatus).ToListAsync();
            //进行任务
            var doingTaskItmes = await _experimentTaskRep.DetachedEntities.Where(s => s.ActualStartTime.HasValue && s.ActualStartTime.Value >= dateRange.StartTime && s.ActualStartTime.Value <= dateRange.EndTime && s.ValidStatus && s.Status == ExperimentStatus.Doing).ToListAsync();
            //完成任务
            var completeTaskItmes = await _experimentTaskRep.DetachedEntities.Where(s => s.ActualEndTime.HasValue && s.ActualEndTime.Value >= dateRange.StartTime && s.ActualEndTime.Value <= dateRange.EndTime && s.ValidStatus && s.Status == ExperimentStatus.Finished).ToListAsync();

            foreach (var itme in teams)
            {
                TeamTaskStatisticsOutput model = new TeamTaskStatisticsOutput
                {
                    TeamName = $"{itme.WorkName}-{itme.Name}",
                    TaskCount = taskItmes.Count(s => s.TeamId == itme.Id),
                    NotStartedCount = taskItmes.Count(s => s.TeamId == itme.Id && s.Status == ExperimentStatus.NotStarted),
                    DoingCount = doingTaskItmes.Count(s => s.TeamId == itme.Id),
                    CompleteCount = completeTaskItmes.Count(s => s.TeamId == itme.Id),
                    PassCount = completeTaskItmes.Count(s => s.TeamId == itme.Id && s.Result == ExperimentResult.Pass),
                    NoPassCount = completeTaskItmes.Count(s => s.TeamId == itme.Id && s.Result == ExperimentResult.NoPass),
                };
                if (model.CompleteCount > 0)
                {
                    double failureRate = (double)model.PassCount / model.CompleteCount;
                    model.PassRate = (failureRate * 100).ToString("F2") + "%";
                }
                result.Add(model);
            }

            return result;
        }


        /// <summary>
        /// 获取统计数据
        /// </summary>
        /// <param name="dateType"></param>
        /// <returns></returns>
        [HttpGet("statistics/GetTaskStatisticsData")]
        public async Task<object> GetTaskStatistics(StatisticsDateType dateType)
        {
            var dateRange = GetDates(dateType);

            //开工试验任务
            var startTaskItmes = await _experimentTaskRep.DetachedEntities.Where(s => s.ActualStartTime.HasValue && s.ActualStartTime.Value >= dateRange.StartTime && s.ActualStartTime.Value <= dateRange.EndTime).ToListAsync();

            //完工试验任务
            var completeTaskItmes = await _experimentTaskRep.DetachedEntities.Where(s => s.ActualEndTime.HasValue && s.ActualEndTime.Value >= dateRange.StartTime && s.ActualEndTime.Value <= dateRange.EndTime).ToListAsync();

            //不良品
            var rejectDealItems = await _rejectDealRep.DetachedEntities.Where(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= dateRange.StartTime && s.CreatedTime.Value <= dateRange.EndTime).ToListAsync();

            var items = new List<TaskDayStatisticsOutput>();

            foreach (var day in dateRange.DateList)
            {
                var startTime = day;
                var endTime = day.AddDays(1).AddMilliseconds(-1);
                var dateItmes = startTaskItmes.Count(s => s.ActualStartTime.HasValue && s.ActualStartTime.Value >= startTime && s.ActualStartTime.Value <= endTime);

                items.Add(new TaskDayStatisticsOutput
                {
                    CurrentDate = day.Date.ToString("yyyy-MM-dd"),
                    StartCount = startTaskItmes.Count(s => s.ActualStartTime.HasValue && s.ActualStartTime.Value >= startTime && s.ActualStartTime.Value <= endTime),
                    RejectCount = rejectDealItems.Count(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= startTime && s.CreatedTime.Value <= endTime),
                    CompleteCount = completeTaskItmes.Count(s => s.ActualEndTime.HasValue && s.ActualEndTime.Value >= startTime && s.ActualEndTime.Value <= endTime),
                });
            }
            SeriesBarData series = new SeriesBarData();

            string[] legends = new string[3];
            legends[0] = "开工";
            legends[1] = "报工";
            legends[2] = "不良品";

            series.LegendData = legends;

            series.XAxisData = dateRange.DateList.Select(s => s.ToString("yyyy-MM-dd")).ToList();

            series.yAxisData.Add(new Series { Name = "开工", Type = "line", Data = items.Select(s => s.StartCount).ToList() });
            series.yAxisData.Add(new Series { Name = "报工", Type = "line", Data = items.Select(s => s.CompleteCount).ToList() });
            series.yAxisData.Add(new Series { Name = "不良品", Type = "line", Data = items.Select(s => s.RejectCount).ToList() });

            return series;
        }

        /// <summary>
        /// 仪器状态分布饼图数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("statistics/GetEquipmentStatusStatisticsData")]
        public async Task<object> GetEquipmentStatusStatistics()
        {
            var equipments = await _equipmentRep.DetachedEntities.ToListAsync();

            List<SeriesPieData> series = new List<SeriesPieData>();

            var model = default(EquipmentStatus);

            FieldInfo[] fieldinfo = typeof(EquipmentStatus).GetFields();

            foreach (FieldInfo field in fieldinfo)
            {
                SeriesPieData seriesPie = new SeriesPieData();

                if (!(Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attribute))
                {
                    seriesPie.Name = field.GetValue(model).ToString();
                }
                else
                {
                    seriesPie.Name = attribute.Description;
                }
                seriesPie.Value = equipments.Count(s => s.EquipmentStatus == (EquipmentStatus)field.GetValue(model).GetHashCode());

                if (field.GetValue(model).ToString() != "0")
                {
                    series.Add(seriesPie);
                }
            }

            return series;
        }

        /// <summary>
        /// 仪器厂家分布饼图数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("statistics/GetEquipmentFactoryStatisticsData")]
        public async Task<object> GetEquipmentFactoryStatistics()
        {
            var equipmentFactorys = await _equipmentFactoryRep.DetachedEntities.Where(s => s.ValidStatus).ToListAsync();

            var equipments = await _equipmentRep.DetachedEntities.ToListAsync();

            List<SeriesPieData> series = new List<SeriesPieData>();

            foreach (var item in equipmentFactorys)
            {
                SeriesPieData seriesPie = new SeriesPieData();
                seriesPie.Name = item.Name;

                seriesPie.Value = equipments.Count(s => s.EquipmentFactoryId == item.Id);

                series.Add(seriesPie);
            }

            return series;
        }

        /// <summary>
        /// 仪器分类分布饼图数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("statistics/GetEquipmentCategoryStatisticsData")]
        public async Task<object> GetEquipmentCategoryStatistics()
        {
            var equipmentCategorys = await _equipmentCategoryRep.DetachedEntities.Where(s => s.ValidStatus && s.ParentId == 0).ToListAsync();

            var equipments = await _equipmentRep.DetachedEntities.Include(x => x.EquipmentCategory).ToListAsync();

            List<SeriesPieData> series = new List<SeriesPieData>();

            foreach (var item in equipmentCategorys)
            {
                SeriesPieData seriesPie = new SeriesPieData();
                seriesPie.Name = item.Name;
                seriesPie.Value = equipments.Count(s => s.EquipmentCategory.Pids.Contains(item.Id.ToString()) || s.EquipmentCategoryId == item.Id);
                series.Add(seriesPie);
            }

            return series;
        }

        /// <summary>
        /// 仪器分类状态分布饼图数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("statistics/GetEquipmentCategorySatusStatistics")]
        public async Task<object> GetEquipmentCategorySatusStatistics()
        {
            var equipmentCategorys = await _equipmentCategoryRep.DetachedEntities.Where(s => s.ValidStatus && s.ParentId == 0).ToListAsync();

            var equipments = await _equipmentRep.DetachedEntities.Include(x => x.EquipmentCategory).ToListAsync();

            SeriesBarData series = new SeriesBarData();

            List<EquipmentCategoryStatusCount> itmes = new List<EquipmentCategoryStatusCount>();

            foreach (var item in equipmentCategorys)
            {
                var list = equipments.Where(s => s.EquipmentCategory.Pids.Contains(item.Id.ToString()) || s.EquipmentCategoryId == item.Id).ToList();

                EquipmentCategoryStatusCount model = new EquipmentCategoryStatusCount();
                model.Name = item.Name;
                model.RunCount = list.Count(s => s.EquipmentStatus == EquipmentStatus.Normal || s.EquipmentStatus == EquipmentStatus.RunUnderill);
                model.RepairCount = list.Count(s => s.EquipmentStatus == EquipmentStatus.Repairing || s.EquipmentStatus == EquipmentStatus.reporting);
                model.UselessCount = list.Count(s => s.EquipmentStatus == EquipmentStatus.Useless || s.EquipmentStatus == EquipmentStatus.Stop);

                itmes.Add(model);
            }

            string[] legends = new string[3]; //"运行中的","维修中的","报废中的"
            legends[0] = "正常运行";
            legends[1] = "报修维修";
            legends[2] = "报废停用";

            series.LegendData = legends;

            series.XAxisData = equipmentCategorys.Select(x => x.Name).ToList();

            series.yAxisData.Add(new Series { Name = "正常运行", Type = "bar", Data = itmes.Select(s => s.RunCount).ToList() });
            series.yAxisData.Add(new Series { Name = "报修维修", Type = "bar", Data = itmes.Select(s => s.RepairCount).ToList() });
            series.yAxisData.Add(new Series { Name = "报废停用", Type = "bar", Data = itmes.Select(s => s.UselessCount).ToList() });

            return series;
        }


        /// <summary>
        /// 不良原因分布图
        /// </summary>
        /// <returns></returns>
        [HttpGet("statistics/GetDefectiveReasonStaticsPieData")]
        public async Task<object> GetDefectiveReasonStaticsPieData(StatisticsDateType dateType)
        {
            var dateRange = GetDates(dateType);

            var defectiveReasons = await _defectiveReasonRep.DetachedEntities.Where(s => s.ValidStatus).ToListAsync();

            var rejectItems = await _rejectItemRep.DetachedEntities.Where(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= dateRange.StartTime && s.CreatedTime.Value <= dateRange.EndTime).ToListAsync();

            List<SeriesPieData> series = new List<SeriesPieData>();

            foreach (var item in defectiveReasons)
            {
                SeriesPieData seriesPie = new SeriesPieData();
                seriesPie.Name = item.Reason;
                seriesPie.Value = rejectItems.Count(s => s.Reason == item.Reason);
                series.Add(seriesPie);
            }

            return series;
        }

        /// <summary>
        /// 不良品处理结果分布图
        /// </summary>
        /// <returns></returns>
        [HttpGet("statistics/GetRejectDealResultStaticsPieData")]
        public async Task<object> GetRejectDealResultStaticsPieData(StatisticsDateType dateType)
        {
            var dateRange = GetDates(dateType);

            var rejectDeals = await _rejectDealRep.DetachedEntities.Where(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= dateRange.StartTime && s.CreatedTime.Value <= dateRange.EndTime && !string.IsNullOrWhiteSpace(s.Result)).GroupBy(s => s.Result).ToListAsync();

            List<SeriesPieData> series = new List<SeriesPieData>();

            foreach (var item in rejectDeals)
            {
                SeriesPieData seriesPie = new SeriesPieData();
                seriesPie.Name = item.Key;
                seriesPie.Value = item.Count();
                series.Add(seriesPie);
            }

            return series;
        }

        /// <summary>
        /// 不良品统计
        /// </summary>
        /// <param name="dateType"></param>
        /// <returns></returns>
        [HttpGet("statistics/GetRejectDealStatistics")]
        public async Task<object> GetRejectDealStatistics(StatisticsDateType dateType)
        {
            var rejectDealItems = await _rejectDealRep.DetachedEntities.Include(s => s.ExperimentTask).ToListAsync();

            return new
            {
                RejectCount = rejectDealItems.Count(),
                ProductCount = rejectDealItems.Where(s => s.ExperimentTask.TaskType == ExperimentType.Product).Count(),
                MaterialCount = rejectDealItems.Where(s => s.ExperimentTask.TaskType == ExperimentType.Material).Count(),
                DealCount = rejectDealItems.Where(s => s.Status == RejectDealStatus.Deal).Count(),
                TodoCount = rejectDealItems.Where(s => s.Status == RejectDealStatus.Todo).Count(),
            };
        }



        /// <summary>
        /// 不良品数量按天统计
        /// </summary>
        /// <param name="dateType"></param>
        /// <returns></returns>
        [HttpGet("statistics/GetRejectDealStatisticsData")]
        public async Task<object> GetRejectDealStatisticsData(StatisticsDateType dateType)
        {
            var dateRange = GetDates(dateType);

            //不良品
            var rejectDealItems = await _rejectDealRep.DetachedEntities.Where(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= dateRange.StartTime && s.CreatedTime.Value <= dateRange.EndTime).ToListAsync();

            var dealItems = await _rejectDealRep.DetachedEntities.Where(s => s.Status == RejectDealStatus.Deal && s.DealTime.HasValue && s.DealTime.Value >= dateRange.StartTime && s.DealTime.Value <= dateRange.EndTime).ToListAsync();

            var items = new List<RejectDealDayStatisticsOutput>();

            foreach (var day in dateRange.DateList)
            {
                var startTime = day;
                var endTime = day.AddDays(1).AddMilliseconds(-1);
                var dateItmes = rejectDealItems.Count(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= startTime && s.CreatedTime.Value <= endTime);

                items.Add(new RejectDealDayStatisticsOutput
                {
                    CurrentDate = day.Date.ToString("yyyy-MM-dd"),
                    DealCount = dealItems.Count(s => s.DealTime.HasValue && s.DealTime.Value >= startTime && s.DealTime.Value <= endTime),
                    RejectCount = rejectDealItems.Count(s => s.CreatedTime.HasValue && s.CreatedTime.Value >= startTime && s.CreatedTime.Value <= endTime)
                });
            }
            SeriesBarData series = new SeriesBarData();

            string[] legends = new string[2];
            legends[0] = "新增不良品";
            legends[1] = "处理不良品";

            series.LegendData = legends;

            series.XAxisData = dateRange.DateList.Select(s => s.ToString("yyyy-MM-dd")).ToList();

            series.yAxisData.Add(new Series { Name = "新增不良品", Type = "line", Data = items.Select(s => s.RejectCount).ToList() });
            series.yAxisData.Add(new Series { Name = "处理不良品", Type = "line", Data = items.Select(s => s.DealCount).ToList() });

            return series;
        }


        /// <summary>
        /// 根据类型获取日期集合
        /// </summary>
        /// <param name="dateType"></param>
        /// <returns></returns>
        public static DateRange GetDates(StatisticsDateType dateType)
        {
            var StartTime = DateTime.Now;
            var EndTime = DateTime.Now;
            var now = DateTime.Now.Date;
            if (dateType == StatisticsDateType.Yesterday)
            {
                StartTime = DateTime.Now.Date.AddDays(-1);
                EndTime = StartTime.AddDays(1).AddMilliseconds(-1);
            }
            else if (dateType == StatisticsDateType.Week)
            {
                StartTime = now.AddDays(-6).Date;
                EndTime = now.AddDays(1).AddSeconds(-1);
            }
            else if (dateType == StatisticsDateType.Month)
            {
                StartTime = now.AddDays(-29).Date;
                EndTime = now.AddDays(1).AddSeconds(-1);
            }

            var dates = new List<DateTime>();

            for (DateTime currentDate = StartTime; currentDate <= EndTime; currentDate = currentDate.AddDays(1))
            {
                dates.Add(currentDate.Date);
            }

            return new DateRange
            {
                StartTime = StartTime,
                EndTime = EndTime,
                DateList = dates
            };
        }



    }
}
